package com.bw.attendance.sign

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_attendance.SignIntent
import com.bawei.module_attendance.SignState
import com.bawei.module_attendance.model.SignService

import com.blankj.utilcode.util.LogUtils
import com.bw.attendance.sign.entity.SignEntity
import com.bw.attendance.sign.entity.SignResponseEntity

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.HashMap

class SignViewModel : BaseViewModel<SignIntent>() {
    private val service: SignService by lazy{ SignService() }
    private val _states = MutableStateFlow<SignState>(SignState.Init)//MutableStateFlow可变
    val states: StateFlow<SignState>
        get() = _states


    //请求获取历史记录
    fun requestSignHistory(it :SignIntent.RequestSignHistoryIntent){
        viewModelScope.launch{
            flow {
                val signResponseEntity = service.requestSignHistory(it.requestEntity)
                emit(signResponseEntity)
            }.collect{
                _states.value = SignState.RequestHistorySignSuccessState(it.data)
            }

        }
    }
    //签到
    fun requestSign(it :SignIntent.RequestSignIntent ){

        viewModelScope.launch{
            flow {
                val signResponseEntity = service.requestSign(it.requestEntity)
                emit(signResponseEntity)
            }.collect{
                    _states.value = SignState.RequestSignSuccessState(it)
            }

        }

    }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is SignIntent.RequestSignHistoryIntent ->  requestSignHistory(it)//
                    is SignIntent.RequestSignIntent ->  requestSign(it)//
                }
            }
        }

    }

}